﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Clipper.BLL;
using Clipper.Model;
using Clipper.Model.WorkDataModel;
using Global;
using Clipper.BLL.DetectChain;
using System.Collections.Specialized;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using Clipper.Model.DetectionModel;

namespace Clipper.ClipperUserControl
{
    /// <summary>
    /// UseWorkSheet.xaml 的交互逻辑
    /// </summary>
    public partial class UserWorkSheet : UserControl
    {
        #region --------成员变量-----------

        Model.TestTubeInfo mSelectRemoved = null;
        ListBox mCurrentListBox = null;//当前listbox
        ListBox mLastListBox = null;//上一个listbox
        ObservableCollection<Model.DetectItems> mFisrtItems = null;//拖动时第一个样本的检测项列表   
        Model.TestTubeInfo mCurrentTube = null;
        Model.TestTubeInfo mFirstTube;//第一个选中的Tube,用于判断拖动顺序
        object mItem = null;//当前选中单元格包含的项
        long mEditSampleId = -1;//编辑样本

        BLL.SampleInfo mSampleBll = new BLL.SampleInfo();
        BLL.TestTubeSelfInfo mTestTubeShelfBll = new BLL.TestTubeSelfInfo();

        private ObservableCollection<UserSettedDetectItem> mUserSettedDetectItemList;   // 用户设置的检查项列表

        #endregion --------成员变量-----------
        System.Timers.Timer RelaseTimer = new System.Timers.Timer();
        public delegate void TimerFunc();
        #region 属性
        #endregion

        #region 初始化
        public UserWorkSheet()
        {
            InitializeComponent();
            mUserSettedDetectItemList = new ObservableCollection<UserSettedDetectItem>();
            ServiceProvider.gReactionStripList = new ObservableCollection<ReactionStrip>();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //DataBind();


            RelaseTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                TimerFunc func = new TimerFunc(UpdateStatus);
                Dispatcher.Invoke(func, new Object[] { });
                
                RelaseTimer.Close();
                
            });
            RelaseTimer.Interval = 200;
        }
        public void UpdateStatus()
        {
            detectItemSet1.lsvrelase();
        }

        public void DataBind()
        {
            if (DataContext == null)
            {
                detectItemSet1.DataBind();
                ServiceProvider.WorkSheetVM.TestTubeShelfList = mTestTubeShelfBll.GetFullModelList();
                this.DataContext = ServiceProvider.WorkSheetVM;
            }
            //往展示架上显示试管详细信息
            if (ServiceProvider.WorkSheetVM.SampleTypeSource == null)
            {
                ServiceProvider.WorkSheetVM.SampleTypeSource = new BLL.SampleType().GetModelList("");
            }
            datWorkSheet.ItemsSource = ServiceProvider.WorkSheetVM.TestTubeShelfList[0].TestTubeInfoList;


        }
        #endregion

        #region 检测项、样本操作

        // 单元格切换事件，设置样本后触发
        private void datWorkSheet_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (mFirstTube == null && datWorkSheet.CurrentItem != null)
            {
                mFirstTube = datWorkSheet.CurrentItem as Model.TestTubeInfo;
            }
            if (datWorkSheet.CurrentCell.Column != null)
            {
                int index = datWorkSheet.CurrentCell.Column.DisplayIndex;//当前列
                mItem = datWorkSheet.CurrentCell.Item;//当前单元格
                Model.TestTubeInfo testTube = null;
                testTube = datWorkSheet.CurrentCell.Item as Model.TestTubeInfo;
                if (e.RemovedCells.Count > 0)
                {
                    if (mSelectRemoved != null)
                    {
                        if (mSelectRemoved.SampleID != testTube.SampleID)//是否更改样本号
                        {
                            Model.SampleInfo sample = mSampleBll.GetSampleInfoAndItems(mSelectRemoved.SampleID);
                            if (sample != null && sample.PatientInfo.patientID > 0)//是否存在样本,病人信息id大于0
                            {
                                testTube = mSelectRemoved;
                                testTube.SampleInfo = mSampleBll.GetSampleInfoAndItems(testTube.SampleID);
                                testTube.DetectItems = testTube.SampleInfo.DetectItems;
                            }
                        }
                    }
                }
                switch (index)
                {

                    case 3:
                        DataGridComboBoxColumn templeColumnq = datWorkSheet.SelectedCells.Last().Column as DataGridComboBoxColumn;
                        FrameworkElement templeElementq = templeColumnq.GetCellContent(mItem);

                        break;
                    case 4://检测项列表
                        mCurrentTube = datWorkSheet.CurrentItem as Model.TestTubeInfo;
                        if (mCurrentTube.SampleInfo.PatientInfo.name == null)
                        {
                            DataGridTemplateColumn templeColumn = datWorkSheet.SelectedCells.Last().Column as DataGridTemplateColumn;
                            FrameworkElement templeElement = templeColumn.GetCellContent(mItem);
                            mCurrentListBox = templeColumn.CellTemplate.FindName("lsbDetectItem", templeElement) as ListBox;
                        }
                        else
                        {
                            UIHelper.ShowKeyMessage("DetectItemsNoChange");
                            mCurrentListBox = null;
                        }

                        break;
                    default:
                        mCurrentListBox = null;
                        break;
                }
                mSelectRemoved = datWorkSheet.CurrentCell.Item as Model.TestTubeInfo;
            }
        }

        //添加检测项
        private void detectItemSet1_SelectionChangedEvent(object sender, SelectionChangedEventArgs e)
        {
            if (mCurrentListBox != null)
            {
                //ObservableCollection<Model.DetectItems> _detects = (mCurrentListBox.ItemsSource as ObservableCollection<Model.DetectItems>);
                //var xModel=from x in _detects where x.detectItem==detectItemSet1.CurrentItem.detectItem
                //           select x;
                //Model.DetectItems dd = xModel as Model.DetectItems;
                //if (_detects != null&&!_detects.Contains(detectItemSet1.CurrentItem))
                //{
                //    _detects.Contains(detectItemSet1.CurrentItem);
                //    Model.TestTubeInfo _testTube = (Model.TestTubeInfo)this.datWorkSheet.SelectedCells[0].Item;
                //    _testTube.DetectItems.Add(detectItemSet1.CurrentItem);
                //    mSampleBll.AddSampleItem(_testTube.SampleID, detectItemSet1.CurrentItem.detectItem);
                //}

                Model.TestTubeInfo _testTube = (Model.TestTubeInfo)this.datWorkSheet.SelectedCells[0].Item;

                //此处控制所选的值是否跟当前值是否一样  开始
                //bool addFlag = true;
                //foreach (Model.DetectItems useItem in _testTube.DetectItems)
                //{
                //    if (useItem.detectItem.Equals(detectItemSet1.CurrentItem.detectItem))
                //    {
                //        //如果存在已有项的检测 退出 不添加
                //        addFlag = false;
                //        break;
                //    }

                //}
                //if (addFlag)
                //{
                _testTube.DetectItems.Add(detectItemSet1.CurrentItem);
                    mSampleBll.AddSampleItem(_testTube.SampleID, detectItemSet1.CurrentItem.detectItem);
                //}
                //
                RelaseTimer.Start();
            }

        }
        //删除检测项
        private void ListBoxItem_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            Model.TestTubeInfo _testTube = (Model.TestTubeInfo)this.datWorkSheet.SelectedCells[0].Item;
            //_testTube.DetectItems.Remove(mCurrentListBox.SelectedItem as Model.DetectItems);
            Model.DetectItems _detectItem = (Model.DetectItems)((ListBoxItem)sender).Content;
            _testTube.DetectItems.Remove(_detectItem);
            mSampleBll.DeleteSampleItem(_testTube.SampleID, _detectItem.detectItem);
        }
        // 同一行填充检测项
        private void datWorkSheet_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            Model.TestTubeInfo testTube = null;
            testTube = datWorkSheet.CurrentCell.Item as Model.TestTubeInfo;

            switch (e.Column.DisplayIndex)
            {
                case 2:
                    string newValue = (e.EditingElement as TextBox).Text;
                    if (newValue != "")
                    {
                        if (mSelectRemoved != null)
                        {
                            if (testTube != null)
                            {
                                if (mSelectRemoved.holeNumber == testTube.holeNumber)
                                {
                                    testTube.SampleInfo = mSampleBll.GetSampleInfoAndItems(long.Parse(newValue));
                                    testTube.DetectItems = testTube.SampleInfo.DetectItems;
                                    (datWorkSheet.CurrentCell.Item as Model.TestTubeInfo).SampleInfo = testTube.SampleInfo;
                                    (datWorkSheet.CurrentCell.Item as Model.TestTubeInfo).DetectItems = testTube.DetectItems;
                                }
                            }
                        }
                    }
                    break;
                case 3:
                    mEditSampleId = mSelectRemoved.SampleID;
                    string ff = (e.EditingElement as ComboBox).SelectedValue.ToString();
                    testTube.SampleInfo.sampleType = byte.Parse(ff);
                    mSampleBll.Update(testTube.SampleInfo);

                    break;
            }
        }
        //拖动离开检测项列表事件
        private void lsbDetectItem_MouseLeave(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (datWorkSheet.CurrentItem != null && datWorkSheet.SelectedCells.Count == 1)
                {
                    mCurrentTube = datWorkSheet.CurrentItem as Model.TestTubeInfo;
                    if (mCurrentTube.SampleInfo.PatientInfo.name == null)
                    {
                        DataGridTemplateColumn templeColumn = datWorkSheet.SelectedCells.First().Column as DataGridTemplateColumn;
                        FrameworkElement templeElement = templeColumn.GetCellContent(mItem);
                        mLastListBox = templeColumn.CellTemplate.FindName("lsbDetectItem", templeElement) as ListBox;

                        if (mLastListBox != null)
                        {
                            mFisrtItems = (mCurrentListBox.ItemsSource as ObservableCollection<Model.DetectItems>);
                            Console.WriteLine(mCurrentListBox.Items.Count);
                        }
                    }
                }
            }
        }
        //拖动抬起事件，拖拉检测项结束
        private void lsbDetectItem_MouseUp(object sender, MouseButtonEventArgs e)
        {

            bool firstCell = true;
            int countOther = (from cell in datWorkSheet.SelectedCells
                              where cell.Column.DisplayIndex != 4
                              select cell).Count();
            if (countOther == 0 && datWorkSheet.SelectedCells.Count > 1)//选中的非检测项列列单元格的数量，有一个则不处理
            {
                if (mFirstTube != null)
                {
                    if (mFirstTube.testTubeID == (datWorkSheet.SelectedCells.First().Item as Model.TestTubeInfo).testTubeID)
                    {
                        foreach (DataGridCellInfo cell in datWorkSheet.SelectedCells)
                        {
                            FillItems(ref firstCell, cell);
                        }
                    }
                    else
                    {
                        foreach (DataGridCellInfo cell in datWorkSheet.SelectedCells.Reverse())
                        {
                            FillItems(ref firstCell, cell);
                        }
                    }
                }
            }
            mFirstTube = null;
        }

        private void FillItems(ref bool firstCell, DataGridCellInfo cell)
        {
            if (firstCell)
            {
                firstCell = false;
            }
            else
            {
                Model.TestTubeInfo _testTubeInfo = cell.Item as Model.TestTubeInfo;
                DataGridTemplateColumn templeColumn = cell.Column as DataGridTemplateColumn;
                if (templeColumn != null)
                {
                    _testTubeInfo.DetectItems.Clear();
                    mSampleBll.DeleteAllSampleItem(_testTubeInfo.SampleID);
                    if (mFisrtItems != null)
                    {
                        foreach (Model.DetectItems item in mFisrtItems)
                        {
                            _testTubeInfo.DetectItems.Add(item);
                            mSampleBll.AddSampleItem(_testTubeInfo.SampleID, item.detectItem);
                        }
                    }
                    else
                    {
                        MessageBox.Show("检测项为空");
                    }
                }
            }
        }

        #endregion

        #region 试管架操作
        //试管架选择事件
        private void lsbTubeSelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ServiceProvider.WorkSheetVM.SampleTypeSource == null)
            {
                ServiceProvider.WorkSheetVM.SampleTypeSource = new BLL.SampleType().GetModelList("");
            }
            Model.TestTubeSelfInfo tubeshelf = lsbTubeSelf.SelectedItem as Model.TestTubeSelfInfo;
            if (tubeshelf != null)
            {
                ServiceProvider.WorkSheetVM.CurrentTestTubeShelf = tubeshelf;
            }
        }

        // 添加试管架,直接保存到数据库
        private void addShelf_Click(object sender, RoutedEventArgs e)
        {
            //if (this.txtBarcode.Text == "")
            //{
            //    UIHelper.ShowKeyMessage("BarcodeNotNull");
            //    return;
            //}
            //if (mTestTubeShelfBll.ExistBarcode(txtBarcode.Text))
            //{
            //    UIHelper.ShowKeyMessage("BarcodeRepeat");
            //    return;
            //}
            ctrlBusy.IsBusy = true;
            BackgroundWorker _backWorker = new BackgroundWorker();
            Model.TestTubeSelfInfo tubeshelf = new Model.TestTubeSelfInfo();
            //tubeshelf.barcode = this.txtBarcode.Text;
            tubeshelf.TestTubeInfoList = new ObservableCollection<Model.TestTubeInfo>();
            //---------样本号累加
            int _testShelfCount = ServiceProvider.WorkSheetVM.TestTubeShelfList.Count;
            long _lastSampleID = mSampleBll.GetLastTubeSampleId();
            ServiceProvider.WorkSheetVM.TestTubeShelfList.Add(tubeshelf);
            _backWorker.DoWork += (ss, ee) =>
            {
                if (tubeshelf.TestTubeInfoList != null)
                {
                    for (int i = 1; i <= 15; i++)
                    {
                        Model.TestTubeInfo tube = new Model.TestTubeInfo()
                        {
                            holeNumber = i,
                            ShelfBarcode = tubeshelf.barcode,
                            DetectItems = new ObservableCollection<Model.DetectItems>()
                        };
                        tube.SampleID = _lastSampleID + i;
                        if (!mSampleBll.Exists(tube.SampleID))//不存在是保存样本
                        {
                            tube.SampleInfo = new Model.SampleInfo()
                            {
                                sampleID = tube.SampleID,
                                createTime = DateTime.Now,
                                sampleType = 0//样本类型默认为普通样本
                            };
                            mSampleBll.Add(tube.SampleInfo);
                        }
                        else //或者查找已经存在样本的检测项
                        {
                            tube.SampleInfo = mSampleBll.GetSampleInfoAndItems(tube.SampleID);
                            tube.DetectItems = tube.SampleInfo.DetectItems;
                        }
                        tubeshelf.TestTubeInfoList.Add(tube);
                    }
                    mTestTubeShelfBll.SaveTubeShelfList(tubeshelf);
                }
            };
            _backWorker.RunWorkerCompleted += (ss, ee) =>
                {
                    lsbTubeSelf.SelectedIndex = lsbTubeSelf.Items.Count - 1;
                    ctrlBusy.IsBusy = false;
                };
            _backWorker.RunWorkerAsync();
        }

        // 保存试管架信息
        private void saveShelf_Click(object sender, RoutedEventArgs e)
        {
            //BackgroundWorker back = new BackgroundWorker();
            //back.WorkerReportsProgress = true;
            //bool result = false;
            //prgSaveTube.Visibility = Visibility.Visible;
            //prgSaveTube.Value = 0;
            //back.DoWork += (ss, ee) =>
            //    {
            //        double count=ServiceProvider.WorkSheetVM.TestTubeShelfList.Count*10;
            //        double saveCount=0;
            //        foreach (Model.TestTubeSelfInfo shelf in ServiceProvider.WorkSheetVM.TestTubeShelfList)
            //        {
            //            saveCount++;
            //            if (mTestTubeShelfBll.Exists(shelf.testTubeSelfID))
            //            {
            //                result = mTestTubeShelfBll.Update(shelf);
            //            }
            //            else
            //            {
            //                result = mTestTubeShelfBll.Add(shelf);
            //            }
            //            if (result == false)
            //                break;
            //            double percent = Math.Ceiling(saveCount / count * 100);
            //            back.ReportProgress(int.Parse(percent.ToString()));
            //        }
            //    };
            //back.ProgressChanged += (ss, ee) =>
            //    {
            //        prgSaveTube.Value = ee.ProgressPercentage;
            //    };
            //back.RunWorkerCompleted += (ss, ee) =>
            //    {

            //        UIHelper.SuccessOrFailTip(result, "Save");
            //        prgSaveTube.Visibility = Visibility.Hidden;
            //    };
            //back.RunWorkerAsync();
        }

        // 删除试管架
        private void deleteShelf_Click(object sender, RoutedEventArgs e)
        {
            if (ServiceProvider.WorkSheetVM.CurrentTestTubeShelf != null)
            {
                bool result = false;
                //ServiceProvider.Monitor.IsBusy = true;
                ctrlBusy.IsBusy = true;

                BackgroundWorker back = new BackgroundWorker();
                back.DoWork += (ss, ee) =>
                    {
                        result = mTestTubeShelfBll.DeleteTubeShelfList(ServiceProvider.WorkSheetVM.CurrentTestTubeShelf);
                    };
                back.RunWorkerCompleted += (ss, ee) =>
                    {
                        UIHelper.SuccessOrFailTip(result, "DeleteTip");
                        ServiceProvider.WorkSheetVM.TestTubeShelfList.Remove(ServiceProvider.WorkSheetVM.CurrentTestTubeShelf);
                        ServiceProvider.WorkSheetVM.CurrentTestTubeShelf = null;
                        //ServiceProvider.Monitor.IsBusy = false;
                        ctrlBusy.IsBusy = false;
                    };
                back.RunWorkerAsync();
            }
            else
            {
                UIHelper.ShowKeyMessage("SelectShelf");
            }
        }
        #endregion

        private void txtBarcode_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void btnAllBarcode_Click(object sender, RoutedEventArgs e)
        {
            Model.TestTubeSelfInfo testTubeShelf = new Model.TestTubeSelfInfo();
            Communication.SampleControl sampleControl = AddReagent1AndSample.Sample;
            string firstBarcode = "";
            //sampleControl.WaitStatus(sampleControl.Reset());
            while (true)
            {
                for (int i = 0; i < 9; i++)
                {
                    sampleControl.WaitStatus(sampleControl.Position());

                    //sampleControl.WaitStatus(sampleControl.CheckTube());
                    //if (sampleControl.IsTube)
                    //{
                    Model.TestTubeInfo tube = new Model.TestTubeInfo();
                    for (int j = 0; j < 3; j++)
                    {
                        sampleControl.WaitStatus(sampleControl.GetBarcode());
                        Thread.Sleep(2000);
                        if (sampleControl.Barcode != "")
                        {
                            if (firstBarcode == "")//记录第一个条码
                            {
                                firstBarcode = sampleControl.Barcode;
                            }
                            else if (firstBarcode == sampleControl.Barcode)//循环一周了
                            {
                                return;
                            }
                            else
                            {
                                tube.SampleInfo.sampleBarcode = sampleControl.Barcode;
                                testTubeShelf.TestTubeInfoList.Add(tube);
                            }
                            break;
                        }
                    }
                    //}
                }
                sampleControl.WaitStatus(sampleControl.ChangeShelf());
            }
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            Model.TestTubeInfo first_testTube = (Model.TestTubeInfo)this.datWorkSheet.SelectedCells[0].Item;

            List<Model.SampleDetectItems> models = new List<SampleDetectItems>();
            //SampleDetectItems sampleItem = new SampleDetectItems();
            for (int i = 1; i < 15; i++)
            {
                foreach (Model.DetectItems firstuseItem in first_testTube.DetectItems)
                {
                    Model.TestTubeInfo _testTube = (Model.TestTubeInfo)datWorkSheet.Items[i];
                    bool addFlag = true;
                    foreach (Model.DetectItems useItem in _testTube.DetectItems)
                    {
                        if (useItem.detectItem.Equals(firstuseItem.detectItem))
                        {
                            //如果存在已有项的检测 退出 不添加
                            addFlag = false;
                            break;
                        }
                    }
                    if (addFlag)
                    {
                        _testTube.DetectItems.Add(firstuseItem);
                        //mSampleBll.AddSampleItem(_testTube.SampleID, firstuseItem.detectItem);
                        SampleDetectItems sampleItem = new SampleDetectItems();  //添加样本检测信息对象
                        sampleItem.DetectItem = firstuseItem.detectItem;
                        sampleItem.SampleID = _testTube.SampleID;
                        models.Add(sampleItem);
                    }
                }
            }
            mSampleBll.BatchAddSampleItem(models);
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Model.TestTubeInfo first_testTube = (Model.TestTubeInfo)this.datWorkSheet.SelectedCells[0].Item;
            StringBuilder MyStringBuilder = new StringBuilder();
            for (int i = 0; i < 15; i++)
            {
                Model.TestTubeInfo _testTube = (Model.TestTubeInfo)datWorkSheet.Items[i];
                _testTube.DetectItems.Clear();
                MyStringBuilder.Append(",");
                MyStringBuilder.Append(_testTube.SampleID);
            }
            if (MyStringBuilder.Length>0) MyStringBuilder.Remove(0, 1);
            mSampleBll.DeleteList(MyStringBuilder.ToString());

        }

        private void button2_Loaded(object sender, RoutedEventArgs e)
        {
            //button2.Visibility = Visibility.Collapsed;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            detectItemSet1.lsvrelase();
        }

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {
            ServiceProvider.CupStrip.Clear();
            ServiceProvider.CupStrip = new ObservableCollection<CupStrip>();

            for (int i = 0; i < 4; i++)
            {
                CupStrip strip = new CupStrip();
                //if (i == 0) //置孔位加载状态
                //{
                //strip.setStatus(CupStrip.ReactionStripStatusEnum.LOAD);
                //}
                strip.setStatus(CupStrip.ReactionStripStatusEnum.UNLOAD);
                strip.StripSeat = i;

                for (int j = 0; j < 4; j++)
                {
                    Cup cup = new Cup();
                    //if (i == 0) //置孔位状态
                    //{
                    //cup.setStatus(Cup.CupHoleStatusEnum.FULL);
                    //}
                    cup.setStatus(Cup.CupHoleStatusEnum.EMPTY);
                    cup.HoleSeat = j;
                    cup.inStripSeat = i;
                    strip.Cups.Add(cup);
                }
                ServiceProvider.CupStrip.Add(strip);
            }
        }
    }
}
